<template>
  <div>
    <div
      class="gva-search-box"
    >
      <el-form
        ref="elSearchFormRef"
        :inline="true"
        :model="searchInfo"
        class="demo-form-inline"
        :rules="searchRule"
        @keyup.enter="onSubmit"
      >
        <!-- <el-form-item
          label="创建日期"
          prop="createdAt"
        >
          <template #label>
            <span>
              创建日期
              <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
                <el-icon><QuestionFilled /></el-icon>
              </el-tooltip>
            </span>
          </template>
          <el-date-picker
            v-model="searchInfo.startCreatedAt"
            type="datetime"
            placeholder="开始日期"
            :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"
          />
          —
          <el-date-picker
            v-model="searchInfo.endCreatedAt"
            type="datetime"
            placeholder="结束日期"
            :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"
          />
        </el-form-item> -->

        <el-form-item
          prop="name"
        >
          <el-input
            v-model="searchInfo.name"
            placeholder="请输入配置名称"
          />

        </el-form-item>
        <el-form-item
          prop="type"
        >
          <el-select
            v-model="searchInfo.type"
            placeholder="请选择类型"
            style="width: 150px;"
          >
            <el-option
              v-for="item in configTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          prop="flag"
        >
          <el-select
            v-model="searchInfo.flag"
            placeholder="请选择范围"
            style="width: 150px;"
          >
            <el-option
              v-for="item in configFlagOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="search"
            @click="onSubmit"
          >查询</el-button>
          <el-button
            icon="refresh"
            @click="onReset"
          >重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div
      v-if="selectPlatform == 2"
      class="gva-table-box"
    >
      <div class="gva-btn-list">
        <el-button
          type="primary"
          icon="plus"
          @click="openDialog"
        >新增</el-button>
        <!-- <el-popover
          v-model:visible="deleteVisible"
          :disabled="!multipleSelection.length"
          placement="top"
          width="160"
        >
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px;">
            <el-button
              type="primary"
              link
              @click="deleteVisible = false"
            >取消</el-button>
            <el-button
              type="primary"
              @click="onDelete"
            >确定</el-button>
          </div>
          <template #reference>
            <el-button
              icon="delete"
              style="margin-left: 10px;"
              :disabled="!multipleSelection.length"
              @click="deleteVisible = true"
            >删除</el-button>
          </template>
        </el-popover> -->
      </div>
      <el-table
        ref="multipleTable"
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="id"
        border
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column
          type="selection"
          width="55"
        /> -->

        <el-table-column
          align="left"
          label="更新时间"
        >
          <template #default="scope">{{ formatDate(scope.row.updated_at) }}</template>
        </el-table-column>
        <el-table-column
          align="left"
          label="配置表名称"
          prop="name"
        />
        <el-table-column
          align="left"
          label="描述"
          prop="desc"
        />
        <el-table-column
          align="left"
          label="类型"
          prop="type"
        >
          <template #default="scope">
            {{ filterDict(scope.row.type,configTypeOptions) }}
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="服务器"
        >
          <template #default="scope">
            {{ scope.row.type == 2 ? scope.row.server_name : '无' }}
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="配置详情"
        >
          <template #default="scope">
            <el-button
              v-if="scope.row.url && scope.row.url !== ''"
              type="primary"
              link
              class="table-button"
              @click="showConfig(scope.row)"
            >
              <el-icon style="margin-right: 5px"><Briefcase /></el-icon>
              查看详情
            </el-button>
            <el-button
              v-else
              link
              type="danger"
              class="table-button"
            >
              <el-icon style="margin-right: 5px"><PhoneFilled /></el-icon>
              暂未上传
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="适用范围"
          prop="flag"
        >
          <template #default="scope">
            {{ filterDict(scope.row.flag,configFlagOptions) }}
          </template>
        </el-table-column>
        <el-table-column
          align="left"
          label="操作"
          fixed="right"
          width="300"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              class="table-button"
              @click="getDetails(scope.row)"
            >
              <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
              导入配置
            </el-button>
            <el-button
              type="primary"
              link
              icon="edit"
              class="table-button"
              @click="updateQmConfigFunc(scope.row)"
            >变更</el-button>
            <el-button
              type="primary"
              link
              icon="delete"
              @click="deleteRow(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="gva-pagination">
        <el-pagination
          layout="total, prev, pager, next, jumper"
          :current-page="page"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogFormVisible"
      :before-close="closeDialog"
      :title="type==='create'?'添加':'修改'"
      destroy-on-close
    >
      <el-scrollbar height="500px">
        <el-form
          ref="elFormRef"
          :model="formData"
          label-position="right"
          :rules="rule"
          label-width="120px"
        >
          <el-form-item
            label="配置表名称:"
            prop="name"
          >
            <el-input
              v-model="formData.name"
              :clearable="true"
              placeholder="请输入配置表名称"
            />
          </el-form-item>
          <el-form-item
            label="类型"
            prop="type"
          >
            <el-select
              v-model="formData.type"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in configTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="formData.type == 2"
            label="服务器:"
            prop="server_id"
          >
            <el-select
              v-model.number="formData.server_id"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in serverList"
                :key="item.id"
                :label="item.server_name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="适用范围:"
            prop="flag"
          >
            <el-select
              v-model="formData.flag"
              placeholder="请选择"
              clearable
            >
              <el-option
                v-for="item in configFlagOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="描述:"
            prop="name"
          >
            <el-input
              v-model="formData.desc"
              :clearable="true"
              type="textarea"
              placeholder="请输入描述"
            />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog">取 消</el-button>
          <el-button
            type="primary"
            @click="enterDialog"
          >确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog
      v-model="detailShow"
      style="width: 95%"
      lock-scroll
      :before-close="closeDetailShow"
      title="导入配置"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-scrollbar height="800px">
        <el-divider />
        <!-- <el-upload
          ref="uploadRef"
          style="margin-top: 20px"
          :limit="1"
          :show-file-list="false"
          action=""
          :on-exceed="handleExceed"
          :http-request="httpExcelRequest"
        >
          <template #trigger>
            <el-button type="primary">上传配置</el-button>
          </template>
          <span v-if="columnDataMap.length > 0">
            <el-button
              class="ml-3"
              type="success"
              @click="submitUpload"
            >
              确认上传
            </el-button>
            <el-button
              class="ml-3"
              type="warning"
              @click="clearColumnDataMap"
            >
              清空配置
            </el-button>
          </span>

        </el-upload> -->
        <div style="margin-bottom: 20px;">
          <form
            id="fromCont"
            method="post"
          >
            <div
              class="fileUpload"
              @click="inputChange"
            >
              选择文件
              <input
                v-show="false"
                id="file"
                ref="FileInput"
                multiple="multiple"
                type="file"
                @change="choseFile"
              >
            </div>

          </form>
          <el-button
            :disabled="limitFileSize"
            type="primary"
            class="uploadBtn"
            @click="getFile"
          >上传文件</el-button>
        </div>

        <div class="list">
          <transition
            name="list"
            tag="p"
          >
            <div
              v-if="file"
              class="list-item"
            >
              <el-icon>
                <document />
              </el-icon>
              <span>{{ file.name }}</span>
              <span class="percentage">{{ percentage }}%</span>
              <el-progress
                :show-text="false"
                :text-inside="false"
                :stroke-width="2"
                :percentage="percentage"
              />
            </div>
          </transition>
        </div>
        <el-table
          style="margin-top: 20px"
          :data="columnDataMap"
        >
          <el-table-column
            v-for="(item,index) in columnNames"
            :key="index"
            :label="item.label"
            :prop="item.prop"
          /></el-table>
      </el-scrollbar>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  createQmConfig,
  deleteQmConfig,
  updateQmConfig,
  findQmConfig,
  getQmConfigList,
} from '@/api/qmConfig'

import {
  getQmServerList
} from '@/api/qmServer'

import {
  findFile,
  breakpointContinueFinish,
  removeChunk,
  breakpointContinue
} from '@/api/breakpoint'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { Axios } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive, watch } from 'vue'
import * as xlsx from 'xlsx'
import SparkMD5 from 'spark-md5'

const excelList = ref([])
const configId = ref('')

const file = ref(null)
const fileMd5 = ref('')
const formDataList = ref([])
const waitUpLoad = ref([])
const waitNum = ref(NaN)
const limitFileSize = ref(false)
const percentage = ref(0)
const percentageFlage = ref(true)

defineOptions({
  name: 'QmConfig'
})

// 自动化生成的字典（可能为空）以及字段
const platformOptions = ref([])
const configTypeOptions = ref([])
const configFlagOptions = ref([])
const formData = ref({
  gameHash: '',
  platformId: undefined,
  name: '',
  type: undefined,
  flag: undefined,
  desc: '',
  server_id: undefined,
})

// 验证规则
const rule = reactive({
  name: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],
  type: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },

  ],
  flag: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },

  ],
  desc: [{
    required: true,
    message: '',
    trigger: ['input', 'blur'],
  },
  {
    whitespace: true,
    message: '不能只输入空格',
    trigger: ['input', 'blur'],
  }
  ],

})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

const selectPlatform = ref(1)
const isPlatform = () => {
  const platform = localStorage.getItem('platform')
  console.log(platform)
  if (platform == 0 || platform == '' || platform == null || platform == undefined) {
    ElMessage({
      type: 'error',
      message: '请先选择渠道'
    })
    // setTimeout(() => {
    //   window.location.href = '/#/layout/dashboard'
    // }, 1000)
  } else {
    selectPlatform.value = 2
  }
}

isPlatform()

// =========== 表格控制部分 ===========
const page = ref(1)
const total = ref(0)
const pageSize = ref(10)
const tableData = ref([])
const searchInfo = ref({})

// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 搜索
const onSubmit = () => {
  isPlatform()
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    getTableData()
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

const showConfig = (row) => {
  // 新窗口打开
  window.open(row.url)
}

// 查询
const getTableData = async() => {
  isPlatform()
  const table = await getQmConfigList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
  }
}

getTableData()

const submitUpload = () => {
  const uploadUrl = import.meta.env.VITE_BASE_PATH + ':' + import.meta.env.VITE_SERVER_PORT + import.meta.env.VITE_BASE_API + '/qmConfig/uploadConfig'
  console.log(uploadUrl)
  axios.post({
    url: uploadUrl,
    headers: {
      'Content-Type': 'multipart/form-data'
    },
    data: {
      configId: configId.value,
      file: configFile.value
    }
  }).then(res => {
    if (res.data.code === 0) {
      ElMessage({
        type: 'success',
        message: '上传成功'
      })
      closeDetailShow()
      getTableData()
    }
  })
  // uploadConfig({
  //   configId: configId.value,
  //   file: configFile.value,
  // }).then(res => {
  //   if (res.code === 0) {
  //     ElMessage({
  //       type: 'success',
  //       message: '上传成功'
  //     })
  //     closeDetailShow()
  //     getTableData()
  //   }
  // })
}

const uploadRef = ref(null)

const serverList = ref([])
const getServerList = async() => {
  const res = await getQmServerList({ page: 1, pageSize: 1000, status: 1 })
  if (res.code === 0) {
    serverList.value = res.data.list
  }
}
getServerList()
// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async() => {
  platformOptions.value = await getDictFunc('platform')
  configTypeOptions.value = await getDictFunc('config_type')
  configFlagOptions.value = await getDictFunc('config_flag')
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 多选数据
const multipleSelection = ref([])
// 多选
const handleSelectionChange = (val) => {
  multipleSelection.value = val
}

const handleExceed = () => {
  ElMessage({
    type: 'warning',
    message: '若要重新上传,请先清空配置'
  })
}

// 删除行
const deleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    deleteQmConfigFunc(row)
  })
}

const columnNames = ref([])
const columnDataMap = ref([])

function convertToTableColumns(labels, props) {
  // 确保 labels 和 props 数组长度相同
  if (labels.length !== props.length) {
    throw new Error('Labels and props arrays must have the same length')
  }

  // 创建一个空数组来存储转换后的结果
  const result = []

  // 遍历 labels 和 props 数组，并将它们转换成对象的形式
  for (let i = 0; i < labels.length; i++) {
    result.push({
      label: labels[i],
      prop: props[i]
    })
  }

  return result
}

const readFile = (file) => {
  return new Promise((resolve) => {
    const reader = new FileReader()
    reader.readAsBinaryString(file)
    reader.onload = (ev) => {
      resolve(ev.target?.result)
    }
  })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateQmConfigFunc = async(row) => {
  const res = await findQmConfig({ id: row.id })
  type.value = 'update'
  if (res.code === 0) {
    formData.value = res.data
    dialogFormVisible.value = true
  }
}

// 删除行
const deleteQmConfigFunc = async(row) => {
  const res = await deleteQmConfig({ id: row.id })
  if (res.code === 0) {
    ElMessage({
      type: 'success',
      message: '删除成功'
    })
    if (tableData.value.length === 1 && page.value > 1) {
      page.value--
    }
    getTableData()
  }
}

// 弹窗控制标记
const dialogFormVisible = ref(false)

// 查看详情控制标记
const detailShow = ref(false)

// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}

// 打开详情
const getDetails = async(row) => {
  configId.value = row.id
  openDetailShow()
}

// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  file.value = null
  fileMd5.value = ''
  formDataList.value = []
  waitUpLoad.value = []
  waitNum.value = NaN
  limitFileSize.value = false
  percentage.value = 0
  percentageFlage.value = true

  columnNames.value = []
  columnDataMap.value = []

  // 刷新数据
  getTableData()
}

// 打开弹窗
const openDialog = () => {
  isPlatform()
  type.value = 'create'
  dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
  dialogFormVisible.value = false
  formData.value = {
    gameHash: '',
    platformId: undefined,
    name: '',
    type: undefined,
    flag: undefined,
    server_id: undefined,
  }
}
// 弹窗确定
const enterDialog = async() => {
  elFormRef.value?.validate(async(valid) => {
    if (!valid) return

    if (formData.value.type === 2 && !formData.value.server_id) {
      ElMessage({
        type: 'warning',
        message: '请选择服务器'
      })
      return
    }
    let res
    switch (type.value) {
      case 'create':
        res = await createQmConfig(formData.value)
        break
      case 'update':
        res = await updateQmConfig(formData.value)
        break
      default:
        res = await createQmConfig(formData.value)
        break
    }
    if (res.code === 0) {
      ElMessage({
        type: 'success',
        message: '创建/更改成功'
      })
      closeDialog()
      getTableData()
    }
  })
}

const timestamp = ref(0)
// 选中文件的函数
const choseFile = async(e) => {
  const fileR = new FileReader() // 创建一个reader用来读取文件流
  const fileInput = e.target.files[0] // 获取当前文件
  const maxSize = 100 * 1024 * 1024
  file.value = fileInput // file 丢全局方便后面用 可以改进为func传参形式
  const fileName = file.value.name.split('.')
  timestamp.value = Math.floor(new Date().getTime() / 1000)
  const newFileName = fileName[0] + '-' + timestamp.value + '.' + fileName[1]
  percentage.value = 0
  if (file.value.size < maxSize) {
    fileR.readAsArrayBuffer(file.value) // 把文件读成ArrayBuffer  主要为了保持跟后端的流一致
    fileR.onload = async e => {
      // 读成arrayBuffer的回调 e 为方法自带参数 相当于 dom的e 流存在e.target.result 中
      const blob = e.target.result
      const spark = new SparkMD5.ArrayBuffer() // 创建md5制造工具 （md5用于检测文件一致性 这里不懂就打电话问我）
      spark.append(blob) // 文件流丢进工具
      fileMd5.value = spark.end() // 工具结束 产生一个a 总文件的md5
      const FileSliceCap = 1 * 1024 * 1024 // 分片字节数
      let start = 0 // 定义分片开始切的地方
      let end = 0 // 每片结束切的地方a
      let i = 0 // 第几片
      formDataList.value = [] // 分片存储的一个池子 丢全局
      while (end < file.value.size) {
        // 当结尾数字大于文件总size的时候 结束切片
        start = i * FileSliceCap // 计算每片开始位置
        end = (i + 1) * FileSliceCap // 计算每片结束位置
        var fileSlice = file.value.slice(start, end) // 开始切  file.slice 为 h5方法 对文件切片 参数为 起止字节数
        const formData = new window.FormData() // 创建FormData用于存储传给后端的信息
        formData.append('fileMd5', fileMd5.value + '-' + timestamp.value) // 存储总文件的Md5 让后端知道自己是谁的切片
        formData.append('file', fileSlice) // 当前的切片
        formData.append('chunkNumber', i) // 当前是第几片
        formData.append('fileName', newFileName) // 当前文件的文件名 用于后端文件切片的命名  formData.appen 为 formData对象添加参数的方法
        formDataList.value.push({ key: i, formData }) // 把当前切片信息 自己是第几片 存入我们方才准备好的池子
        i++
      }
      // 获取时间戳
      const params = {
        fileName: newFileName,
        fileMd5: fileMd5.value + '-' + timestamp.value,
        chunkTotal: formDataList.value.length
      }
      const res = await findFile(params)
      // 全部切完以后 发一个请求给后端 拉当前文件后台存储的切片信息 用于检测有多少上传成功的切片
      const finishList = res.data.file.ExaFileChunk // 上传成功的切片
      const IsFinish = res.data.file.IsFinish // 是否是同文件不同命 （文件md5相同 文件名不同 则默认是同一个文件但是不同文件名 此时后台数据库只需要拷贝一下数据库文件即可 不需要上传文件 即秒传功能）
      if (!IsFinish) {
        // 当是断点续传时候
        waitUpLoad.value = formDataList.value.filter(all => {
          return !(
            finishList &&
              finishList.some(fi => fi.FileChunkNumber === all.key)
          ) // 找出需要上传的切片
        })
      } else {
        waitUpLoad.value = [] // 秒传则没有需要上传的切片
        ElMessage.success('文件已秒传')
      }

      waitNum.value = waitUpLoad.value.length // 记录长度用于百分比展示
    }
  } else {
    limitFileSize.value = true
    ElMessage('请上传小于100M文件')
  }

  columnDataMap.value = []
  columnNames.value = []

  const configFile = fileInput
  const dataBinary = await readFile(configFile)
  const workBook = xlsx.read(dataBinary, { type: 'binary', cellDates: true })
  const workSheet = workBook.Sheets[workBook.SheetNames[0]]
  const excelData = xlsx.utils.sheet_to_json(workSheet, { header: 1 })
  excelList.value = excelData
  console.log(excelList.value)
  // 只把数组的第一行作为表头 第二行作为数据名

  const labels = excelData[1]
  const props = excelData[1]
  const tableColumns = convertToTableColumns(labels, props)
  columnNames.value = tableColumns

  const dataNames = excelData[1]
  const columnData = excelData.slice(2)

  // 只展示前10条数据
  columnDataMap.value = columnData.map((item, index) => {
    // 超过10条数据不显示
    if (index > 9) return
    const obj = {}
    dataNames.forEach((name, index) => {
      obj[name] = item[index]
    })
    return obj
  })

  columnDataMap.value = columnDataMap.value.filter(item => item)
}

const getFile = () => {
  // 确定按钮
  if (file.value === null) {
    ElMessage('请先上传文件')
    return
  }
  if (percentage.value === 100) {
    percentageFlage.value = false
  }
  sliceFile() // 上传切片
}

const sliceFile = () => {
  waitUpLoad.value &&
    waitUpLoad.value.forEach(item => {
      // 需要上传的切片
      item.formData.append('chunkTotal', formDataList.value.length) // 切片总数携带给后台 总有用的
      const fileR = new FileReader() // 功能同上
      const fileF = item.formData.get('file')
      fileR.readAsArrayBuffer(fileF)
      fileR.onload = e => {
        const spark = new SparkMD5.ArrayBuffer()
        spark.append(e.target.result)
        item.formData.append('chunkMd5', spark.end() + '-' + timestamp.value) // 获取当前切片md5 后端用于验证切片完整性
        upLoadFileSlice(item)
      }
    })
}

watch(() => waitNum.value, () => { percentage.value = Math.floor(((formDataList.value.length - waitNum.value) / formDataList.value.length) * 100) })

const upLoadFileSlice = async(item) => {
  // 切片上传
  const fileRe = await breakpointContinue(item.formData)
  if (fileRe.code !== 0) {
    return
  }
  waitNum.value-- // 百分数增加
  if (waitNum.value === 0) {
    const fileName = file.value.name.split('.')
    const newFileName = fileName[0] + '-' + timestamp.value + '.' + fileName[1]
    // 切片传完以后 合成文件
    const params = {
      fileName: newFileName,
      fileMd5: fileMd5.value + '-' + timestamp.value,
      configId: configId.value
    }
    const res = await breakpointContinueFinish(params)
    if (res.code === 0) {
      // 合成文件过后 删除缓存切片
      const params = {
        fileName: newFileName,
        fileMd5: fileMd5.value + '-' + timestamp.value,
        filePath: res.data.filePath,
      }
      ElMessage.success('上传成功')
      await removeChunk(params)
    }
  }
}

const FileInput = ref(null)
const inputChange = () => {
  FileInput.value.dispatchEvent(new MouseEvent('click'))
}

</script>

<style lang='scss' scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
// li {
//   display: inline-block;
//   margin: 0 10px;
// }
a {
  color: #42b983;
}
#fromCont{
  display: inline-block;
}
.fileUpload{
    padding: 3px 10px;
    font-size: 12px;
    height: 20px;
    line-height: 20px;
    position: relative;
    cursor: pointer;
    color: #000;
    border: 1px solid #c1c1c1;
    border-radius: 4px;
    overflow: hidden;
    display: inline-block;
    input{
      position: absolute;
      font-size: 100px;
      right: 0;
      top: 0;
      opacity: 0;
      cursor: pointer;
    }
}
 .fileName{
    display: inline-block;
    vertical-align: top;
    margin: 6px 15px 0 15px;
  }
  .uploadBtn{
    position: relative;
    top: -10px;
    margin-left: 15px;
  }
  .tips{
    margin-top: 30px;
    font-size: 14px;
    font-weight: 400;
    color: #606266;
  }
  .el-divider{
    margin: 0 0 30px 0;
  }

 .list{
   margin-top:15px;
 }
 .list-item {
  display: block;
  margin-right: 10px;
  color: #606266;
  line-height: 25px;
  margin-bottom: 5px;
  width: 40%;
   .percentage{
          float: right;
        }
}
.list-enter-active, .list-leave-active {
  transition: all 1s;
}
.list-enter, .list-leave-to
/* .list-leave-active for below version 2.1.8 */ {
  opacity: 0;
  transform: translateY(-30px);
}
</style>

